﻿@{
    ViewData["Title"] = "About";
    Layout = null;
}

<style>
    body {
        font-family: 'Arial', sans-serif;
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        line-height: 1.6;
    }

    h1 {
        color: #333;
        text-align: center;
    }

    .container {
        background-color: #f9f9f9;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .input-group {
        display: flex;
        margin-bottom: 20px;
    }

    input {
        flex: 1;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px 0 0 4px;
        font-size: 16px;
    }

    button {
        padding: 10px 15px;
        background-color: #4CAF50;
        color: white;
        border: none;
        cursor: pointer;
        font-size: 16px;
    }

        button:hover {
            background-color: #45a049;
        }

    .btn-add {
        border-radius: 0 4px 4px 0;
        margin-left: 5px;
    }

    .action-buttons {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
    }

    .action-btn {
        background-color: #2196F3;
    }

        .action-btn:hover {
            background-color: #0b7dda;
        }

    .btn-download {
        background-color: #ff9800;
    }

        .btn-download:hover {
            background-color: #e68a00;
        }

    ul {
        list-style-type: none;
        padding: 0;
        border: 1px solid #ddd;
        border-radius: 4px;
        min-height: 100px;
    }

    li {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: white;
        cursor: move;
        user-select: none;
        transition: all 0.3s ease;
    }

        li.dragging {
            opacity: 0.5;
            background: #f0f0f0;
        }

    .move-buttons {
        display: flex;
        gap: 5px;
    }

    .move-btn {
        background-color: #9e9e9e;
        color: white;
        border: none;
        border-radius: 4px;
        padding: 2px 8px;
        cursor: pointer;
        font-size: 12px;
    }

        .move-btn:hover {
            background-color: #757575;
        }

    li:last-child {
        border-bottom: none;
    }

    .delete-btn {
        background-color: #f44336;
        color: white;
        border: none;
        border-radius: 4px;
        padding: 2px 8px;
        cursor: pointer;
    }

        .delete-btn:hover {
            background-color: #d32f2f;
        }

    .message {
        margin-top: 15px;
        padding: 10px;
        border-radius: 4px;
        display: none;
    }

    .success {
        background-color: #dff0d8;
        color: #3c763d;
    }

    .error {
        background-color: #f2dede;
        color: #a94442;
    }
</style>
<div class="container">
    <h1>名单排序工具</h1>

    <div class="input-group">
        <input type="text" id="nameInput" placeholder="输入姓名">
        <button class="btn-add" onclick="addName()">添加</button>
        <button class="btn-add" onclick="fetchNames('ResultNames')">初始化默认名单</button>
    </div>

    <div id="message" class="message"></div>
    <div class="action-buttons">
        <button class="action-btn" onclick="sortAscending()">升序排序</button>
        <button class="action-btn" onclick="sortDescending()">降序排序</button>
        <button class="btn-download" onclick="saveToTxt()">下载TXT名单文件</button>

        <button class="btn-download" onclick="saveData()">保存</button>
    </div>

    <ul id="nameList"></ul>
</div>

<script>
    let names = [];


    // 使用fetch获取名单数据
    function fetchNames(res) {
        showMessage('正在加载名单...', 'success');

        fetch('/Duty/' + res)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data && data.length > 0) {
                    names = data;
                    renderList();
                    showMessage('名单加载成功', 'success');
                } else {
                    throw new Error('无效的数据格式');
                }
            })
            .catch(error => {
                console.error('获取名单失败:', error);
                showMessage(`加载失败: ${error.message}`, 'error');
                renderList(); // 显示空状态
            });
    }

    // 初始化时加载名单
    fetchNames('ResNames');

    function addName() {
        const input = document.getElementById('nameInput');
        const name = input.value.trim();

        if (name === '') {
            showMessage('请输入有效的姓名', 'error');
            return;
        }

        names.push(name);
        input.value = '';
        renderList();
        showMessage(`"${name}" 已添加到列表`, 'success');
    }

    function renderList() {
        const list = document.getElementById('nameList');
        list.innerHTML = '';

        if (names.length === 0) {
            list.innerHTML = '<li style="color: #999; text-align: center;">名单为空</li>';
            return;
        }

        names.forEach((name, index) => {
            const li = document.createElement('li');
            li.draggable = true;
            li.dataset.index = index;
            li.innerHTML = `
                            <span>${name}</span>
                            <div class="move-buttons">
                                <button class="move-btn" onclick="moveUp(${index})" ${index === 0 ? 'disabled' : ''}>↑</button>
                                <button class="move-btn" onclick="moveDown(${index})" ${index === names.length - 1 ? 'disabled' : ''}>↓</button>
                                <button class="delete-btn" onclick="removeName(${index})">删除</button>
                            </div>
                        `;

            // 添加拖拽事件
            li.addEventListener('dragstart', handleDragStart);
            li.addEventListener('dragover', handleDragOver);
            li.addEventListener('dragend', handleDragEnd);
            li.addEventListener('drop', handleDrop);

            list.appendChild(li);
        });
    }

    // 拖拽相关函数
    let draggedItem = null;

    function handleDragStart(e) {
        draggedItem = this;
        this.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', this.innerHTML);
    }

    function handleDragOver(e) {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
        const targetItem = e.target.closest('li');
        if (targetItem && targetItem !== draggedItem) {
            const bounding = targetItem.getBoundingClientRect();
            const offset = e.clientY - bounding.top - bounding.height / 2;
            if (offset < 0) {
                targetItem.parentNode.insertBefore(draggedItem, targetItem);
            } else {
                targetItem.parentNode.insertBefore(draggedItem, targetItem.nextSibling);
            }
        }
    }

    function handleDragEnd() {
        this.classList.remove('dragging');
        updateNamesOrder();
    }

    function handleDrop(e) {
        e.preventDefault();
    }

    function updateNamesOrder() {
        const list = document.getElementById('nameList');
        const newNames = [];
        const items = list.querySelectorAll('li');

        items.forEach(item => {
            if (item.dataset.index) {
                newNames.push(names[item.dataset.index]);
            }
        });

        names = newNames;
        renderList();
        showMessage('名单顺序已更新', 'success');
    }

    // 上移/下移函数
    function moveUp(index) {
        if (index > 0) {
            [names[index], names[index - 1]] = [names[index - 1], names[index]];
            renderList();
            showMessage(`"${names[index]}" 已上移`, 'success');
        }
    }

    function moveDown(index) {
        if (index < names.length - 1) {
            [names[index], names[index + 1]] = [names[index + 1], names[index]];
            renderList();
            showMessage(`"${names[index]}" 已下移`, 'success');
        }
    }

    function removeName(index) {
        const removedName = names[index];
        names.splice(index, 1);
        renderList();
        showMessage(`"${removedName}" 已从列表中删除`, 'success');
    }

    function sortAscending() {
        if (names.length === 0) {
            showMessage('名单为空，无法排序', 'error');
            return;
        }

        names.sort((a, b) => a.localeCompare(b));
        renderList();
        showMessage('已按升序排序', 'success');
    }

    function sortDescending() {
        if (names.length === 0) {
            showMessage('名单为空，无法排序', 'error');
            return;
        }

        names.sort((a, b) => b.localeCompare(a));
        renderList();
        showMessage('已按降序排序', 'success');
    }

    function saveToTxt() {
        if (names.length === 0) {
            showMessage('名单为空，无法保存', 'error');
            return;
        }

        const content = names.join('\n');
        const blob = new Blob([content], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = 'sorted_names.txt';
        document.body.appendChild(a);
        a.click();

        setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }, 100);

        showMessage('名单已保存为TXT文件', 'success');
    }

    function saveData() {
        if (names.length === 0) {
            showMessage('名单为空，无法保存', 'error');
            return;
        }

        showMessage('正在保存名单...', 'success');

        // 在实际应用中，这里应该替换为真实的API端点
        fetch("/Duty/SaveData", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                names: names,
                timestamp: new Date().toISOString()
            })
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`保存失败，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showMessage('名单保存成功', 'success');
                } else {
                    throw new Error(data.message || '保存失败');
                }
            })
            .catch(error => {
                console.error('保存失败:', error);
                showMessage(`保存失败: ${error.message}`, 'error');
            });
    }

    function showMessage(text, type) {
        const messageDiv = document.getElementById('message');
        messageDiv.textContent = text;
        messageDiv.className = 'message ' + type;
        messageDiv.style.display = 'block';

        setTimeout(() => {
            messageDiv.style.display = 'none';
        }, 3000);
    }

    // 初始化空列表显示
    renderList();
</script>